# -*- coding: utf-8 -*-
"""
@project: SYL-Index-Sys
@desc:
"""

from models import File, User
import os
import pandas as pd
from flask import Blueprint, request, render_template, redirect, url_for, jsonify
from flask_login import login_user, login_required, current_user, logout_user
from models import Role, User, Subject, Point, Record
from app import login_manager
import json


view = Blueprint('view', __name__)


@view.route('/view/all-records')
@login_required
def view_all_records():
    records = Record.query.all()
    data = []
    for record in records:
        temp = {}
        temp['id'] = record.id
        temp['point'] = record.point_id
        temp['file_name'] = record.file_name
        temp['record_type'] = record.record_type
        user = User.query.filter_by(id=record.user_id).first()
        temp['username'] = user.username
        temp['upload_time'] = str(record.upload_time)
        temp['op_type'] = record.op_type
        data.append(temp)
    return json.dumps({"data":data}, ensure_ascii=False)

@view.route('/view/record', methods=['POST'])
@login_required
def view_records():
    request_data = json.loads(request.get_data().decode("utf-8"))
    point_id = request_data['id']
    subject = request_data['subject']
    records = Record.query.filter_by(point_id=point_id, record_type=subject).limit(6).all()
    data = []
    for record in records:
        user = User.query.filter_by(id=record.user_id).first()
        upload_time = record.upload_time
        op_type = record.op_type
        # record_str = '  '.join([user.name, str(upload_time), op_type])
        data.append({ 'name': user.name, 'time': str(upload_time), 'op': op_type })
    return json.dumps({"data":data}, ensure_ascii=False)

@view.route('/view/<point_id>', methods=['GET', 'POST'])
@login_required
def view_point_detail(point_id):
    """
    加载一流大学数据指标
    :return:
    """
    request_data = json.loads(request.get_data().decode("utf-8"))
    subject = request_data['subject']
    # base_path = '/api/data/fill_data/'
    base_path = '/api/'
    file = File.query.filter_by(point=point_id, file_type=subject).first() # 查看文件
    if file:
        file_path = os.path.join(base_path, file.path[2:])
        # if point_id.startswith('D'):
        #     # file_path = os.path.join(base_path, 'university/', file.name)
        # elif point_id.startswith('X'):
        #     # file_path = os.path.join(base_path, 'subject/'+str(subject) + '/',file.name)
        print(file_path)
        return json.dumps({"url": file_path}, ensure_ascii=False)
    else:
        return json.dumps({'status_code':404,
                            'reason':'文件没有找到.'})

@view.route('/view/test', methods=['GET'])
@login_required
def index():
    return json.dumps({"name": current_user.name,
                       "department":current_user.department},
                      ensure_ascii=False)

@view.route('/view/university-index', methods=['GET'])
@login_required
def view_university_index():
    # 此处根据用户权限，展示不同的地方
    role_id = current_user.role_id # 获取用户角色信息
    if role_id == 1: # 学校管理员
        points = Point.query.filter_by(point_type='D').all()
    elif role_id == 2: # 大学管理员,只会显示与其绑定的
        points = Point.query.filter_by(point_type='D', user_id = current_user.id).all()
    else:
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    res = []
    for point in points:
        data_json = {}
        data_json['id'] = point.id
        data_json['project'] = point.project
        data_json['factor'] = point.factor
        data_json['point'] = point.point
        data_json['content'] = point.content
        data_json['explain'] = point.explain

        can_view = False
        file = File.query.filter_by(point=point.id).first()
        if file and os.path.exists(file.path):
            can_view = True
        # 是否可以查看
        data_json['can_view'] = can_view
        res.append(data_json)
    return json.dumps({'data':res}, ensure_ascii=False)

# 加载学科列表
@view.route('/view/subject-list')
@login_required
def view_subject_list(): # 加载学科列表
    role_id = current_user.role_id # 用户角色
    if role_id == 1: # 系统管理员
        subjects = Subject.query.all() # 加载所有学科
    elif role_id == 2: # 一流大学填报
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)
    else: # 学科填报
        subjects = Subject.query.filter_by(user_id = current_user.id).all() # 根据用户id进行过滤
    data = []
    for i, s in enumerate(subjects):
        temp = {}
        temp['id'] = s.id
        temp['code'] = s.code
        temp['subject'] = s.name # 学科数据
        data.append(temp)
    return json.dumps({"data":data}, ensure_ascii=False)

# 查看学科指标
@view.route('/view/subject-index', methods=['GET', 'POST'])
@login_required
def view_subject_index():
    role_id = current_user.role_id # 用户角色
    if role_id == 2: # 大学指标管理员，没有资格查看
        return json.dumps({"status_code":403, "info":"您没有权限浏览该项目"}, ensure_ascii=False)

    # request_data = json.loads(request.get_data().decode('utf-8'))
    subject = request.args.get('subject') # 学科
    points = Point.query.filter_by(point_type='X').all()
    res = []
    for point in points:
        data_json = {}
        data_json['id'] = point.id
        data_json['project'] = point.project
        data_json['factor'] = point.factor
        data_json['point'] = point.point
        data_json['content'] = point.content
        data_json['explain'] = point.explain
        can_view = False
        file = File.query.filter_by(point=point.id, file_type=subject).first()
        if file and os.path.exists(file.path):
            can_view = True
        data_json['can_view'] = can_view
        res.append(data_json)
    return json.dumps({'data':res}, ensure_ascii=False)

